package bai2.com.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import javax.swing.JOptionPane;

public class MyRemoteServer extends UnicastRemoteObject implements
		ServerCommandInterface {

	private static final long serialVersionUID = -8192635922547252895L;
	private static int BUFFER_SIZE = 1024 * 4;
	public static final String REMOTE_SERVER = "remote_server";

	protected MyRemoteServer() throws RemoteException {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public boolean upload(File file) throws IOException {
		MyprocessBar myprocessBar = new MyprocessBar();
		myprocessBar.setVisible(true);
		Socket socket = new Socket("127.0.0.1", 9999);
		FileInputStream fileInputStream = new FileInputStream(file);
		OutputStream outputStream = socket.getOutputStream();
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(
				outputStream);
		objectOutputStream.writeObject(file.getName());
		byte[] buffer = new byte[BUFFER_SIZE];
		int count = 0;
		int total = 0;
		double fileSize = file.length();
		while ((count = fileInputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, count);
			int values = (int) ((1.0 * total / fileSize) * 100);
			total += count;
			myprocessBar.setProgressValue(values);
		}
		outputStream.flush();
		outputStream.close();
		fileInputStream.close();
		socket.close();
		myprocessBar.setProgressValue(100);
		JOptionPane.showMessageDialog(myprocessBar, "Upload Finish");
		myprocessBar.dispose();
		return false;
	}

}
